package cn.liutao.websocket;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
public class SocketServer extends WebSocketServer {

    private static CopyOnWriteArraySet<WebSocket> websockets = new CopyOnWriteArraySet<>();

    private static volatile SocketServer socketServer;
    private static  final int PORT=8008;

    private SocketServer(){

    }

    public static SocketServer getInstance(){
        if (socketServer==null){
            synchronized (SocketServer.class){
                if (socketServer==null){
                    try {
                        socketServer = new SocketServer(PORT);
                    } catch (UnknownHostException e) {
                        log.error("webSocket服务启动失败");
                    }
                }
            }
        }
        return socketServer;
    }

    public SocketServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
    }

    public SocketServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conn.send("连接成功");
        websockets.add(conn);
        log.info("客户端{}与服务器获取连接成功,当前连接数为：{},当前连接为：{}",conn,websockets.size(),this);
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        websockets.remove(conn);
        log.info("客户端{}与服务器断开连接,当前连接数为：{}",conn,websockets.size());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        log.info("服务器接收到来自客户端的消息{}",message);
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        if (conn != null) {
            log.error("发生错误");
        }

    }

    @Override
    public void onStart() {
        log.info("webSocket服务器启用");
    }

    public void sendMessage(String message){
        for (WebSocket websocket : websockets) {
            log.info("服务器向客户端发送了消息【{}】",message);
            websocket.send(message);
        }
    }

}

